<script setup lang="ts">
  import { ref, watch, shallowRef, onBeforeUnmount } from 'vue';
  import { useRoute } from 'vue-router';
  // import DOMPurify from 'dompurify';
  import { Message, Avatar } from '@arco-design/web-vue';
  import { queryArticleCommentsList } from '/@/api/app/article';
  import { queryArticleInfo, addComment, postCommentStar } from '/@/api/article';
  import type { ArticleRecord, CommentRecord } from '/@/api/model/articleModel';
  import { Editor } from '@wangeditor/editor-for-vue';
  import { type IEditorConfig, type IDomEditor, SlateNode } from '@wangeditor/editor';
  import { Anchor, AnchorLink, Card, Affix } from '@arco-design/web-vue';
  import PostLeft from '/@/components/PostLeft.vue';
  import UserInfo from '/@/components/UserInfo.vue';
  import RelatedArticles from '/@/components/RelatedArticles.vue';
  import CommentList from '/@/components/Comment/src/CommentList.vue';
  import { useUserStore } from '/@/store/modules/user';
  import CommentAction from '/@/components/Comment/src/CommentAction.vue';

  const userStore = useUserStore();
  const route = useRoute();
  const articleId = ref<number>();
  const articleInfo = ref<ArticleRecord>();
  const isLoading = ref(false);
  const editorRef = shallowRef<IDomEditor>();
  const editorConfig: Partial<IEditorConfig> = {
    readOnly: true,
  };
  interface HeaderRecord {
    href: string;
    text: string;
    type: string;
  }
  const headersRef = ref<HeaderRecord[]>([]);

  const onEditorChange = (editor: IDomEditor) => {
    const headers = editor.getElemsByTypePrefix('header');

    // 标题目录
    if (headers.length) {
      headersRef.value = [];
      headers.forEach((header) => {
        const text = SlateNode.string(header);
        headersRef.value.push({
          href: '#' + header.id,
          text,
          type: (header as any).type,
        });
      });
    }
  };

  const handleCreated = (editor: IDomEditor) => {
    editorRef.value = editor; // 记录 editor 实例，重要！
  };

  onBeforeUnmount(() => {
    const editor = editorRef.value;
    if (editor == null) return;
    editor.destroy();
  });

  watch(
    () => route.params.id,
    (id) => {
      articleId.value = parseInt(Array.isArray(id) ? id[0] : id, 10) ?? 0;
    },
    { immediate: true },
  );
  watch(
    [articleId],
    async ([articleId]) => {
      if (articleId) {
        isLoading.value = true;
        articleInfo.value = await queryArticleInfo({ id: articleId });
        isLoading.value = false;
        reloadCommentList();
      }
    },
    { immediate: true },
  );

  // const clean = computed(() => {
  //   return DOMPurify.sanitize(articleInfo.value?.content);
  // });

  const commentListRef = ref<CommentRecord[]>([]);
  const orderRef = ref<number>(0);

  const reloadCommentList = async () => {
    if (!articleInfo.value) {
      return;
    }
    const data = await queryArticleCommentsList({
      article_id: articleInfo.value.id,
      ord: orderRef.value,
    });
    // item.commentList = data.map((raw) => {
    //   return {
    //     raw,
    //     stared: raw.stared,
    //     isCommenting: false,
    //   };
    // });
    commentListRef.value = data;
  };

  const onOrderChange = (value: number) => {
    orderRef.value = value;
    reloadCommentList();
  };

  const onComment = async (item: ArticleRecord | null, comment?: string, file?: string) => {
    if (!userStore.userInfo) {
      Message.error('请先登录');
      return;
    }
    if (!comment) {
      return;
    }
    if (!articleInfo.value) {
      return;
    }

    try {
      await addComment({
        content: comment,
        article_id: articleInfo.value.id,
        image: file,
        to_user_id: articleInfo.value.user_id,
        user_id: userStore.userInfo.id,
      });
      Message.success('评论成功');
      await reloadCommentList();
    } catch (error) {
      Message.error((error as Error).message || '评论失败');
    }
  };

  const onViewUser = (item: CommentRecord) => {
    window.open(`/user/${item.user_id}`, '_blank');
    // router.push(`/user/${item.user_id}`);
  };

  const onViewToUser = (item: CommentRecord) => {
    window.open(`/user/${item.to_user_id}`, '_blank');
    // router.push(`/user/${item.user_id}`);
  };

  const onListComment = async (
    item: ArticleRecord | null,
    commentItem: Partial<CommentRecord>,
    comment?: string,
    file?: string,
    topComment?: Partial<CommentRecord>,
  ) => {
    if (!userStore.userInfo) {
      Message.error('请先登录');
      return;
    }
    if (!comment) {
      return;
    }
    if (!articleInfo.value) {
      return;
    }

    try {
      await addComment({
        content: comment,
        article_id: articleInfo.value.id,
        to_comment_id: commentItem.id,
        image: file,
        top_id: topComment ? topComment.id : commentItem.id,
        to_user_id: commentItem.user_id,
      });
      Message.success('评论成功');
      await reloadCommentList();
    } catch (error) {
      Message.error((error as Error).message || '评论失败');
    }
  };

  const onListStar = async (
    item: ArticleRecord | null,
    commentItem: Partial<CommentRecord>,
    cancel: boolean,
  ) => {
    const data = await postCommentStar({
      comment_id: commentItem.id as number,
    });
    commentItem.star = data.star;
    commentItem.stared = !cancel;
  };
</script>

<template>
  <div>
    <a-row :gutter="20">
      <a-col :span="2" class="flex items-center justify-center">
        <Affix :offsetTop="100" class="mt-[10px]">
          <PostLeft class="mt-[60px]" />
        </Affix>
      </a-col>
      <a-col :span="16">
        <a-card :bordered="false" class="p-[18px]">
          <div class="text-[#252933] text-[28px] font-bold">{{ articleInfo?.title }}</div>

          <div class="box-border !flex mt-[15px]">
            <a-avatar
              :size="58"
              class="mr-[12px] flex items-center justify-center border border-solid border-[rgba(0,0,0,0.2)] bg-transparent"
            >
              <img alt="avatar" :src="articleInfo?.user_icon" />
            </a-avatar>
            <div class="w-[calc(100%-76px)] user-info">
              <div class="text-[18px] font-bold">
                <span>{{ articleInfo?.user_name }}</span>
              </div>
              <div class="user-desc leading-[30px] mb-4 text-gray-400"
                >{{ articleInfo?.updateTime }} 阅读 {{ articleInfo?.read }}</div
              >
            </div>
          </div>
          <!-- <div v-html="clean" id="basic-demo"></div> -->
          <Editor
            @on-created="handleCreated"
            :modelValue="articleInfo?.content"
            :defaultConfig="editorConfig"
            @onChange="onEditorChange"
          />
          <div class="text-[24px] font-bold text-black">评论</div>
          <div class="mx-auto">
            <div class="flex py-[24px] justify-center items-start">
              <Avatar class="flex-none mr-[16px]" :imageUrl="userStore.userInfo?.icon" />
              <div class="flex-grow flex-shrink">
                <CommentAction
                  @comment="(...args) => onComment(articleInfo || null, ...args)"
                  :auto-focus="false"
                />
              </div>
            </div>
            <CommentList
              :limit="0"
              :order="orderRef"
              @change-order="onOrderChange"
              @view-user="onViewUser"
              @view-to-user="onViewToUser"
              @comment="(...args) => onListComment(articleInfo || null, ...args)"
              @star="(...args) => onListStar(articleInfo || null, ...args)"
              :data="commentListRef"
            />
          </div>
          <a-back-top target-container="#basic-demo" :style="{ position: 'absolute' }" />
        </a-card>
      </a-col>
      <a-col :span="6">
        <UserInfo />

        <RelatedArticles class="mt-[10px]" />

        <Affix :offsetTop="100" class="mt-[10px]">
          <Card title="目录" :bordered="false">
            <Anchor>
              <AnchorLink
                v-for="item in headersRef"
                :href="item.href"
                :key="item.href"
                :class="item.type"
                >{{ item.text }}</AnchorLink
              >
            </Anchor>
          </Card>
        </Affix>
      </a-col>
    </a-row>
  </div>
</template>
